from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKU
from apps.meiduo_admin.serializers.sku import SkuModelSerializer
from apps.meiduo_admin.utils.pagination import MeiduoPagination
from django.db.models import Q
from rest_framework.generics import ListAPIView
from apps.meiduo_admin.serializers.sku import SkuSimpleSerializer


class SkuViewSet(ModelViewSet):
    # queryset = SKU.objects.all()
    def get_queryset(self):
        # 1.接受查询参数中的关键字ｋｅｙｗｏｒｄ
        keyword = self.request.query_params.get('keyword')

        # 2.拼接查询语句
        queryset = SKU.objects
        if keyword:
            # 标题或副标题包含关键字
            queryset = queryset.filter(Q(name__contains=keyword) | Q(caption__contains=keyword))
        queryset = queryset.order_by('-id')
        return queryset

    serializer_class = SkuModelSerializer
    pagination_class = MeiduoPagination


class SkuSimpleView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SkuSimpleSerializer
